#include <iostream>
#include <cstring>
#include <string>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>

using namespace std;

int main()
{
    int sockid = socket(AF_INET, SOCK_STREAM, 0);
    if (sockid < 0)
    {
        cerr << "sockid error" << endl;
        exit(1);
    }

    struct sockaddr_in serverid;
    memset(&serverid, 0, sizeof(serverid));
    serverid.sin_family = AF_INET;
    serverid.sin_port = htons(8088); //指定绑定的端口号为8088
    serverid.sin_addr.s_addr = 0;
    
    int n = bind(sockid, (struct sockaddr*)&serverid, sizeof(serverid));
    if (n < 0) 
    {
        cerr << "bind error" << endl;
        exit(1);
    }

    n = listen(sockid, 3);
    if (n < 0) 
    {
        cerr << "listen error" << endl;
        exit(1);
    }

    while (true)
    {
        struct sockaddr_in perr;
        socklen_t perrsize;
        int sockfd = accept(sockid, (struct sockaddr*)&perr, &perrsize);
        if (sockfd < 0) 
        {
            cerr << "accept error" << endl;
            sleep(1);
            continue;
        }

        char str[1024 * 10];
        // http的请求
        ssize_t n = read(sockfd, str, sizeof(str) - 1);
        if (n > 0)
        {
            str[n] = 0;
            cout << str << endl;
        }
        else 
        {
            cout << "read error" << endl;
            break;
        }
        //http的响应
        char buf[1024] = {0};
        const char* hello = "<h1>hello world</h1>";
        sprintf(buf, "HTTP/1.0 200 OK\r\nContent-Length: %ld\r\n\r\n%s", strlen(hello), hello);
        write(sockfd, buf, strlen(buf));
        sleep(1);
    }
    return 0;
}
